package com.smart.interceptor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.smart.model.Admin;

public class PCAuthorityInterceptor implements HandlerInterceptor{
	@Override
	public boolean preHandle(HttpServletRequest req,
			HttpServletResponse response, Object handler) throws Exception {
		 System.out.println("PCAuthority_check_Interceptor start");
		 HttpSession session=req.getSession();
		 ServletContext sc=req.getServletContext();
		 String Webroot=req.getContextPath();
		 String uri=req.getRequestURI();
		 System.out.println("request uri:"+uri);
         //放过去pc的登录页面和登录数据请求
		 if(uri.equals(Webroot+"/views/pc/login.html")||uri.equals(Webroot+"/pc/login_check")||uri.equals(Webroot+"/pc/user-notifications/repair"))
		 {
			 System.out.println("登录页面，放过");
			 return true;
		 }
		 else
    	 {
			 Object obj=session.getAttribute("admin");
			 if(obj==null) //说明还没登陆
			 {
				 System.out.println("还没登陆，uri:"+uri+"阻止访问");
				 response.sendRedirect("/SmartCommunity/views/pc/login.html");
				 return false;
			 }
			 else
			 {
				 //说明已经登录，判断角色的权限
				 uri=uri.substring(Webroot.length());
				 System.out.println("subUri:"+uri);
				 String role=session.getAttribute("role").toString();
				 boolean canPass=false;
				 Object roleObj=sc.getAttribute(uri);
				 System.out.println("role:"+role);
				 System.out.println("roleObj:"+roleObj);
				 if(roleObj==null) canPass=true;
				 else
				{
					 List<String> roleList=(List<String>)roleObj;
					 for(String s:roleList)
					 {
					   if(s.equals(role))
					   {
						   canPass=true;break;
					   }
					 }
				}
				 if(canPass)
    		     {
    			   System.out.println("uri:"+uri+"有权限，放过去");
    			   return true;
    		     }
    		     else
    	         {
    	    		//如果没有权限访问则返回主页
    	    		System.out.println("uri:"+uri+"没有权限访问");
    	    		response.sendRedirect("/SmartCommunity/views/pc/smart.html");
    	    		return false;
    	         }
			 }
    	 }
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
 		
	}
   
}
